<template>
  <ElDrawer v-model="opened" :title="formType" size="40%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon :disabled="isView">
      <el-row v-if="isAdd">
        <el-col :span="12">
          <ElFormItem label="上级级别" :label-width="labelWidth">
            {{ form.parentName }}
          </ElFormItem>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <ElFormItem label="级别名称" :label-width="labelWidth" prop="levelName">
            <ElInput v-model="form.levelName" />
          </ElFormItem>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <ElFormItem label="级别" :label-width="labelWidth">
            <ElTag>{{ typeLevelName }}</ElTag>
          </ElFormItem>
        </el-col>
      </el-row>
      <el-row v-if="isEdit">
        <el-col :span="12">
          <ElFormItem label="上级级别" :label-width="labelWidth">
            <div class="flex-x-between" style="display: flex">
              <el-input v-model="permKeywords" style="width: 200px" clearable placeholder="物种级别名称">
                <template #prefix>
                  <i-ep-search />
                </template>
              </el-input>
            </div>
            <ElTree
              ref="permTreeRef"
              node-key="code"
              v-model="form.code"
              :data="menuPermOptions"
              :show-checkbox="true"
              :filter-node-method="handlePermFilter"
              :default-expand-all="true"
              :default-checked-keys="leafNodeId"
              :check-strictly="true"
              @check="handleCheck"
              class="mt-5">
              <template #default="{ data }">
                {{ data.levelName }}
              </template>
            </ElTree>
          </ElFormItem>
        </el-col>
      </el-row>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, unref, computed, watch } from 'vue'
import { ElForm, ElFormItem, FormRules, FormInstance, ElTree } from 'element-plus'
import { TbyTypeLevel } from '@api/tby/summarize/typeLevel/interface'
import { getTypeLevelDetail, saveOrUpdateTypeLevel, optionsTypeLevel } from '@api/tby/summarize/typeLevel'
import { FormType } from '@/enums'
const labelWidth = 100
const opened = ref(false)
const loading = ref(true)
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<TbyTypeLevel.Form>>({})
const typeLevelName = ref<any>()
const menuPermOptions = ref<TbyTypeLevel.TreeType[]>([])
const permKeywords = ref('')
const leafNodeId = ref<any>([])
const permTreeRef = ref<InstanceType<typeof ElTree>>()

onMounted(async () => {
  console.log('进来了')
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

// 是否新增
const isEdit = computed(() => {
  return formType.value === FormType.EDIT
})

/** 权限筛选 */
watch(permKeywords, async val => {
  //  一点击就应该取消默认的选中
  leafNodeId.value = []
  // 清空原来的选中状态
  permTreeRef.value?.setCheckedKeys([])
  const { data } = await optionsTypeLevel(val)
  menuPermOptions.value = [{ code: 0, levelName: '顶级分类', levelNames: '', level: 0, parentIds: '', children: data }]
})

const handleCheck = (checkedNodes: any, checkedKeys: any) => {
  // 一点击就应该取消默认的选中
  leafNodeId.value = []
  // // 清空原来的选中状态
  permTreeRef.value?.setCheckedKeys([])
  let newCheck: any[] = checkedKeys.checkedKeys
  if (checkedKeys.checkedKeys.length > 0) {
    if (form.value.code != null) {
      newCheck = []
      // 如果已经选择过，就将已经选择的排除掉
      for (let i = 0; i < checkedKeys.checkedKeys.length; i++) {
        if (form.value.code !== checkedKeys.checkedKeys[i]) {
          newCheck.push(checkedKeys.checkedKeys[i])
        }
      }
    }
    form.value.code = newCheck[0]
    form.value.parentId = newCheck[0]
    leafNodeId.value = newCheck
  }
}

function handlePermFilter(
  value: string,
  data: {
    [key: string]: any
  }
) {
  if (!value) return true
  return data.key.includes(value)
}

const rules = reactive<FormRules>({
  categoryName: [
    { required: true, message: '请输入级别名称', trigger: 'blur' },
    { max: 20, message: '分类名称最大20个字符', trigger: 'blur' }
  ]
})

const open = async (type: FormType, parentId: number, level: number, id?: number, levelName: any) => {
  form.value = {}
  formType.value = type
  opened.value = true
  formRef.value?.clearValidate()
  if (isAdd.value) {
    loading.value = false
    //新增时 级别会在当前等级基础上加一 自动分级
    form.value.level = level + 1
    form.value.parentId = parentId
    if (parentId == 0) {
      form.value.parentName = '顶级'
    } else {
      form.value.parentName = levelName
    }
    viewLevel(form.value.level)
    return
  }
  const { data } = await optionsTypeLevel('')
  menuPermOptions.value = [{ code: 0, levelName: '顶级分类', levelNames: '', level: 0, parentIds: '', children: data }]
  try {
    const { data } = await getTypeLevelDetail(id!)
    loading.value = false
    form.value = data
    if (parentId == 0) {
      form.value.parentName = '顶级'
    } else {
      form.value.parentName = data.parentName
    }
    form.value.code = data.parentId
    leafNodeId.value = [data.parentId]
    viewLevel(form.value.level)
  } finally {
    loading.value = false
  }
}

function close() {
  loading.value = true
  opened.value = false
  form.value = {}
}

function viewLevel(level: any) {
  //回显级别
  if (level === 1) {
    typeLevelName.value = '界'
  } else if (level === 2) {
    typeLevelName.value = '门'
  } else if (level === 3) {
    typeLevelName.value = '纲'
  } else if (level === 4) {
    typeLevelName.value = '目'
  } else if (level === 5) {
    typeLevelName.value = '科'
  } else if (level === 6) {
    typeLevelName.value = '属'
  } else if (level === 7) {
    typeLevelName.value = '种'
  }
}

const onSaveClicked = () => {
  if (!formRef.value) return
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const formData = { ...unref(form) }
    saveOrUpdateTypeLevel(formData).then(() => {
      sendSuccess()
      close()
    })
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>
